<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/18
 * Time: 9:30
 */

namespace app\admin\service;


use app\model\ManagerRoleModel;
use think\facade\Db;

class ManagerRoleService
{
    protected $model;

    public function __construct()
    {
        $this->model = new ManagerRoleModel();
    }

    /**
     * 通过manager_id获取role_id
     * @param $manager_id
     * @return array
     */
    public function findOne($manager_id) {
        return $this->model->where('manager_id', $manager_id)->column('role_id');
    }

    /**
     * 用户-角色关系更新
     * @param $manager_id
     * @param $role_id
     * @return int
     */
    public function update($manager_id, $role_id) {
        $db = new Db();
        $db->startTrans();
        $db_data = $this->findOne($manager_id);
        $delete_data = array_diff($db_data, explode(",", $role_id));
        $insert_data = array_diff(explode(",", $role_id), $db_data);
        $rows = [];
        foreach ($insert_data as $v) {
            $rows[] = ['manager_id' => $manager_id, 'role_id' => $v];
        }
        try {
            // 删除再次提交不存在，但是数据表里存在的
            $this->model->where('manager_id', 'in', $delete_data)->delete();
            // manager_id与role_id写入到manager_role表里
            $this->model->saveAll($rows);
            // 提交事务
            $db->commit();
            return 1;
        } catch (\Exception $e) {
            // 回滚事务
            $db->rollback();
            return 0;
        }
    }

    /**
     * 获取role_id
     * @param $manager_id
     * @return mixed
     */
    public function getRoleIdByManagerId($manager_id) {
        return $this->model->where('manager_id', $manager_id)->value('role_id');
    }
}